package com.hnl.action.talent;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.aware.HNLAuthAware;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.dao.TalentDAO;
import com.hnl.to.Talent;
import com.hnl.to.User;
import com.hnl.to.wrapper.TalentCollectionPageWrapper;
import com.hnl.to.wrapper.TalentWrapper;
import com.hnl.util.DataTablesParamUtility;
import com.hnl.util.JQueryDataTableParamModel;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class LoadAllTalent extends HttpServlet implements HNLAuthAware {
	public static final Logger LOG = LoggerFactory
			.getLogger(LoadAllTalent.class);

	@SuppressWarnings("rawtypes")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		JQueryDataTableParamModel param = DataTablesParamUtility.getParam(req);
		String[] aColumns = { "talent_ID", "talent_ID", "e_first_name",
				"e_last_name", "current_company", "position", "cellphone_1",
				"company_email", "expertise", "modify_user", "c_first_name",
				"c_last_name" };

		String sLimit = null;
		String sOrder = null;
		String sWhere = null;
		String sQuery = null;

		int sEcho = 0;

		PrintWriter writer = resp.getWriter();

		int colLength = aColumns.length;
		if (param != null) {
			sEcho = param.sEcho;
		}

		// paging
		if (param != null && param.iDisplayStart != -1
				&& param.iDisplayLength != -1) {
			sLimit = " LIMIT " + param.iDisplayStart + ","
					+ param.iDisplayLength;
		}

		// ordering
		sOrder = "ORDER BY ";
		if (param == null || param.iSortColumnIndex == 0) {
			// default order by modify_date, col_index=0
			sOrder += "modify_date desc ";
		} else {
			// sorting by columns,starting from col_index=1
			sOrder += aColumns[param.iSortColumnIndex] + " "
					+ param.sSortDirection;
			/*
			 * int iSortingCols = param.iSortingCols; for (int i = 0; i <
			 * iSortingCols; i++) { sOrder += aColumns[param.iSortColumnIndex] +
			 * " " + param.sSortDirection; }
			 */
		}

		if (sOrder == "ORDERBY") {
			sOrder = null;
		}

		// filtering
		sWhere = "WHERE(";
		if (param != null && param.sSearch != null) {
			sWhere = "WHERE (";
			for (int i = 0; i < colLength; i++) {
				sWhere += aColumns[i] + " LIKE '%" + param.sSearch + "%' OR ";
			}
			sWhere = sWhere.substring(0, sWhere.length() - 3);
			sWhere += " OR CONCAT_WS(\" \", e_first_name, e_last_name, c_first_name, c_last_name) LIKE '%"
				+ param.sSearch + "%'";
			sWhere += ") AND ";
		}

		if (req.getParameter("loadType").equals("0")) { // personalList
			HttpSession session = ((HttpServletRequest) req).getSession();
			User user = (User) session.getAttribute(ATTRIBUTE_USER);
			sWhere += " modify_user=" + user.getUserID() + " AND ";
		}
		sWhere += "isdelete=false ";

		/* Individual column filtering */
		/*
		 * for(int i=0;i<colLength;i++){
		 * if(req.getParameter("bSearchable_"+i)=="true"
		 * &&req.getParameter("sSearch_"+i)!=null){ if(sWhere==null){
		 * sWhere=" WHERE "; }else{ sWhere=" AND "; }
		 * sWhere+=aColumns[i]+" LIKE '%"+req.getParameter("sSearch_"+i)+"%' ";
		 * } }
		 */

		/*
		 * SQL Queries Get data to display
		 */
		String selectedCols = "*"; // arrayToString(aColumns, ",");
		sQuery = "SELECT SQL_CALC_FOUND_ROWS " + selectedCols + " FROM TALENT ";

		if (sWhere != null) {
			sQuery += sWhere;
		}
		if (sOrder != null) {
			sQuery += sOrder;
		}
		if (sLimit != null) {
			sQuery += sLimit;
		}

		try {
			TalentDAO talentDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getTalentDAO();
			TalentCollectionPageWrapper talentCollectionPageWrapper = talentDAO
					.loadTalentByPageQuery(sQuery);

			Collection<ArrayList> returnCollection = new ArrayList<ArrayList>();

			for (Talent talent : talentCollectionPageWrapper
					.getTalentCollection()) {
				ArrayList<String> talentInfo = new ArrayList<String>();

				TalentWrapper newTalentWrapper = new TalentWrapper(talent);

				talentInfo.add(" "); // add for checkbox
				talentInfo.add(talent.getTalentId().toString());
				if (talent.geteFirstname().length() == 0
						&& talent.geteLastname().length() == 0) {
					talentInfo.add(talent.getcFirstname() + " "
							+ talent.getcLastname());
				} else {
					talentInfo.add(talent.geteFirstname() + " "
							+ talent.geteLastname());
				}
				talentInfo.add(talent.geteLastname());
				talentInfo.add(talent.getCompany());
				talentInfo.add(talent.getPosition());
				talentInfo.add(talent.getCell1());
				talentInfo.add(talent.getComMail());
				talentInfo.add(talent.getExpertise());
				talentInfo.add(newTalentWrapper.getModifiedUserIDText());
				returnCollection.add(talentInfo);
			}

			Map<String, Object> output = new HashMap<String, Object>();
			output.put("sEcho", sEcho);
			output.put("iTotalRecords", talentCollectionPageWrapper.getTotal());
			output.put("iTotalDisplayRecords",
					talentCollectionPageWrapper.getFilteredTotal());
			output.put("aaData", returnCollection);

			writer.println(JSONResponseUtil.getJSONObjectString(output));
		} catch (DAOException e) {
			LOG.error("error laoding Talent", e);
		}
	}

	private String arrayToString(String[] inputArray, String delimiter) {
		String AsImplodedString;
		if (inputArray.length == 0) {
			AsImplodedString = "";
		} else {
			StringBuffer sb = new StringBuffer();
			sb.append(inputArray[0]);
			for (int i = 1; i < inputArray.length; i++) {
				sb.append(delimiter);
				sb.append(inputArray[i]);
			}
			AsImplodedString = sb.toString();
		}
		return AsImplodedString;
	}
}
